import { NextRequest, NextResponse } from 'next/server';
import { readUsers, writeUsers } from '@/lib/data';
import { verifyToken } from '@/lib/auth';
import bcrypt from 'bcryptjs';

export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const token = request.cookies.get('token')?.value;
    const decoded = verifyToken(token || '');
    
    if (!decoded || !decoded.isAdmin) {
      return NextResponse.json(
        { success: false, message: '需要管理员权限' },
        { status: 403 }
      );
    }

    const { password } = await request.json();

    if (!password) {
      return NextResponse.json(
        { success: false, message: '密码不能为空' },
        { status: 400 }
      );
    }

    const users = readUsers();
    const user = users.find(u => u.id === params.id);

    if (!user) {
      return NextResponse.json(
        { success: false, message: '用户不存在' },
        { status: 404 }
      );
    }

    user.password = await bcrypt.hash(password, 10);
    writeUsers(users);

    return NextResponse.json({ success: true, message: '密码修改成功' });
  } catch (error) {
    return NextResponse.json(
      { success: false, message: '修改密码失败' },
      { status: 500 }
    );
  }
}

